package top.callback.inf.beautyleaf.server.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.callback.inf.beautyleaf.server.dao.UserDao;
import top.callback.inf.beautyleaf.server.entity.UserDO;
import top.callback.inf.beautyleaf.server.model.UserModel;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户服务
 *
 * @author Pengyu Gan
 * CreateDate 2021/3/30
 */
@Slf4j
@Service
@Transactional(readOnly = true, rollbackFor = {Exception.class})
public class UserService {

    @Autowired
    private UserDao userDao;

    /**
     * 新增用户
     * @param userModel {@link UserModel} 用户信息
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean addUser(UserModel userModel) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userModel, userDO);
        return userDao.addUser(userDO) != 0;
    }

    /**
     * 编辑用户
     * @param userModel {@link UserModel} 用户信息
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean editUser(UserModel userModel) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userModel, userDO);
        return userDao.editUser(userDO) != 0;
    }

    /**
     * 删除用户
     * @param userId 用户 ID
     * @return true 成功 false 失败
     */
    @Transactional
    public boolean removeUser(long userId) {
        return userDao.removeUser(userId) != 0;
    }

    /**
     * 查询指定 ID 的用户
     * @param userId 用户 ID
     * @return {@link UserModel} 用户信息
     */
    public UserModel findById(long userId) {
        UserDO userDO = userDao.findById(userId);
        if (null == userDO) {
            throw new RuntimeException("用户不存在");
        }
        UserModel userModel = new UserModel();
        BeanUtils.copyProperties(userDO, userModel);
        return userModel;
    }

    /**
     * 查询所有用户
     * @return 用户列表
     */
    public Set<UserModel> findAll() {
        Set<UserDO> users = userDao.findAll();
        Set<UserModel> userModels = new HashSet<>();
        if (null != users && !users.isEmpty()) {
            userModels = users.stream().map(u -> {
                UserModel userModel = new UserModel();
                BeanUtils.copyProperties(u, userModel);
                return userModel;
            }).collect(Collectors.toSet());
        }
        return userModels;
    }

}
